package com.shisan.tingshu.user.api;

import com.shisan.tingshu.common.execption.ShisanException;
import com.shisan.tingshu.common.login.annotation.TingshuLogin;
import com.shisan.tingshu.common.result.Result;
import com.shisan.tingshu.common.result.ResultCodeEnum;
import com.shisan.tingshu.common.util.AuthContextHolder;
import com.shisan.tingshu.model.user.UserInfo;
import com.shisan.tingshu.user.service.UserInfoService;
import com.shisan.tingshu.vo.user.UserInfoVo;
import io.micrometer.common.util.StringUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @GetMapping("/wxLogin/{code}")
    @Operation(summary = "微信小程序登录")
    public Result wxLogin(@PathVariable(value = "code") String code){

        Map<String, Object> map = userInfoService.wxLogin(code);

        return Result.ok(map);
    }

    @GetMapping("/getUserInfo")
    @Operation(summary = "根据ID获取用户信息")
    @TingshuLogin
    public Result geUserInfo(){
        // 从ThreadLocal中获取userId
        Long userId = AuthContextHolder.getUserId();
        UserInfoVo userInfoVo = userInfoService.getUserInfo(userId);

        return Result.ok(userInfoVo);
    }

    @GetMapping("/refreshToken/getNewAccessToken")
    @Operation(summary = "获取新令牌")
    @TingshuLogin
    public Result getNewAccessToken(){
        Map<String, Object> map = userInfoService.getNewAccessToken();
        String flag = (String) map.get("1");
        if(map != null && StringUtils.isEmpty(flag)) {
            return Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        }

        return Result.ok(map);
    }

    @PostMapping("/updateUser")
    @Operation(summary = "更新用户信息")
    @TingshuLogin
    public Result updateUser(@RequestBody UserInfoVo userInfoVo) {
        userInfoService.updateUser(userInfoVo);
        return Result.ok();
    }
}
